// components/v-upload/index.js
const app = getApp()
Component({
  properties: {
    fileList: {
      type: Array,
      value: [],
      observer: function (newVal) {  // 新增属性变化监听
        this.setData({ tempFileList: newVal })
      }
    },
    accept: {
      type: String,
      value: 'image'
    }
  },

  data: {
    tempFileList: [], // 保持与wxml中变量名一致（驼峰式）
    token: ''
  },
  lifetimes: {
    attached() {
      this.getToken()
    }
  },
  methods: {
    getToken() {
      const config = app.globalData.uploadConfig
      let uploadToken = ''

      //  优先从Storage读取
      try {
        uploadToken = wx.getStorageSync('uploadToken')
        if (uploadToken) {
          config.token = uploadToken // 同步到globalData
          this.setData({ token: uploadToken })
          return
        }
      } catch (e) { }

      // 其次检查globalData
      if (config.token) {
        uploadToken = config.token
        wx.setStorageSync('uploadToken', uploadToken) // 回写Storage
        this.setData({ token: uploadToken })
        return
      }

      //  都没有则请求接口
      this.renewToken()
    },
    renewToken(event) {
      const config = app.globalData.uploadConfig
      app.axios('qiniu', { op: 'qiniu_loadtuken' }).then(res => {
        if (res.statusCode === 200) {
          // 同时存储到两处
          config.token = res.data
          wx.setStorageSync('uploadToken', res.data)

          this.setData({
            token: res.data
          })
          if (event) {
            this.afterRead(event)
          }
        }
      }).catch(err => {
        console.error('获取上传token失败', err)
        this.triggerEvent('error', err)
      })
    },
    afterRead(event) {
      const { file } = event.detail;
      const that = this; // 保存组件实例引用
      const config = app.globalData.uploadConfig
      wx.uploadFile({
        url: config.url,
        filePath: file.url,
        name: 'file',
        formData: {
          token: this.data.token
        },
        success(res) {
          if (res.statusCode == 401) {
            that.renewToken(event)
          } else {
            // 构造新文件对象（根据实际返回数据结构调整）
            if (res.data && res.data.length > 10) {
              const data = JSON.parse(res.data)
              const newFile = {
                isImage: true,
                url: app.globalData.attachBaseUrl + data.key,
                key: data.key,
                id: res.key
              };

              // 通过事件传递新增文件
              that.triggerEvent('change', {
                type: 'add',
                files: [newFile]
              });
            }
          }
        }
      });
    },

    deleteFile(e) {
      const deletedFile = e.detail.file;

      // 通过事件传递删除信息
      this.triggerEvent('change', {
        type: 'remove',
        files: deletedFile
      });

      console.log('删除的文件:', deletedFile);
    }
  }
})